package com.irdstudio.tdp.executor.core.plugin.migrate;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.irdstudio.tdp.executor.core.plugin.migrate.dao.*;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

/**
 * <p>migrateCheckRuleUtil: 检查规则数据<p>
 * @author cjw
 * @date 2020-11-04
 */
public class migrateCheckRuleUtil {


	private static Logger logger = LoggerFactory.getLogger(migrateCheckRuleUtil.class);
	/**
	 * 表数据检查规则插件实现方法
	 * params：migrateCheckRuleList检查规则配置[]
	 */
	public boolean MigrateCheckRulerrz(List<MigrateCheckRule> migrateCheckRuleList,Connection conn){
		boolean result=true;
		try {
			//循环拿到的检查规则数据
			for (int i = 0; i < migrateCheckRuleList.size(); i++) {
				MigrateCheckRule rule=migrateCheckRuleList.get(i);
				MigrateCheckRuleDao migrateCheckRuleDao = new MigrateCheckRuleDao(conn);
				//通过规则中配置sql，获取查询的结果集
				List<Map> selecttablelist = migrateCheckRuleDao.selectTableList(rule);
				Map map=selecttablelist.get(0);
				//结果集第一个字段的值
				int resultcount=0;
				for(Object key : map.keySet()){
					resultcount =MapUtils.getInteger(map,key);
					break;
				}
				//是否符合预期的值
				String check_expect_flag="";
				if(resultcount<=rule.getCheckExpectValue().intValue()){
					check_expect_flag="Y";
				}else{
					check_expect_flag="N";

				}
				//规则sql中带有单引号无法插入需要转义
				char[] rsqls=rule.getCheckRuleSql().toCharArray();
				String rsql="";
				for (int j = 0; j < rsqls.length; j++) {
					if(String.valueOf(rsqls[j]).equals("'")){
						rsql=rsql+"''";
					}else {
						rsql=rsql+String.valueOf(rsqls[j]);
					}
				}
				//现根据ruleid删除已经插入的检查规则结果
				boolean deleteTable= migrateCheckRuleDao.delete(rule.getCheckRuleId());
				if(!deleteTable){
					return  false;
				}
				//插入规则结果集的sql
				boolean insertTable = migrateCheckRuleDao.insertTable(rule,rsql,resultcount,check_expect_flag);
				if(!insertTable){
					return  false;
				}
				//数据治理任务处理'
				if(check_expect_flag.equals("N")){
					//先通过检查规则id查询是否已经生成了一条
					List<Map> gvList = migrateCheckRuleDao.selectGovern(rule.getCheckRuleId());
					if(gvList.size()==0){
						boolean addOrUpdateOrDeleteTable = migrateCheckRuleDao.addOrUpdateOrDeleteTable(rule);
						if(!addOrUpdateOrDeleteTable){
							return  false;
						}
					}
				}
			}
			return result;
		} catch (Exception e) {
			result = false;
			logger.error("检查规则出错！", e);
		}
		return  result;
	}
}
